<template>
  <div id="my">
    <el-drawer title="个人信息" :visible.sync="drawer" :before-close="handleClose">
      <ul>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>账 号：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-input v-model="userInfo.account" :disabled="true"></el-input>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>密 码：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-input v-model="userInfo.password" show-password maxlength="16"></el-input>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>姓 名：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-input v-model="userInfo.fullname" maxlength="10"></el-input>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>性 别：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-select v-model="userInfo.sex" placeholder="请选择" style="width: 100%;">
                  <el-option value="男">男</el-option>
                  <el-option value="女">女</el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>邮 箱：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-input v-model="userInfo.email" maxlength="20"></el-input>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>生 日：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-date-picker v-model="userInfo.birthday" type="date" placeholder="选择日期" style="width: 100%;"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li>
          <el-row>
            <el-col :span="4">
              <div class="grid-content bg-purple">
                <span>地 址：</span>
              </div>
            </el-col>
            <el-col :span="20">
              <div class="grid-content bg-purple-light">
                <el-input v-model="userInfo.address"></el-input>
              </div>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </li>
        <li style="text-align: left;">
          钱包余额：<span class="wallet">{{ userInfo.wallet }}（元）&nbsp;&nbsp;&nbsp;
          </span><el-button size="mini" @click="openWallet(userInfo.id)">充值</el-button>
          <el-divider></el-divider>
        </li>
        <li>
          <el-button plain type="primary" @click="UpdateUser(userInfo.id)">修改个人信息</el-button>

          <el-button plain type="success" @click="gotoOrder()">查看我的订单</el-button>

        </li>
      </ul>
    </el-drawer>

  </div>
</template>

<script>
export default {
  name: 'my',
  data() {
    return {
      drawer: true,
      userInfo: {
        id: '',
        account: '',
        password: '',
        fullname: '',
        sex: '',
        email: '',
        birthday: '',
        address: '',
        wallet: ''
      }, // 存储当前登录用户的信息
    }
  },
  created() {
    const user = localStorage.getItem('userinfo');
    this.$axios.get("http://localhost:3000/users").then(res => {
      this.resinfo = res.data; // 将获取到的用户数据赋值给resinfo
      console.log(this.resinfo);
      // 遍历resinfo数组，找到account等于user的数据
      for (let i = 0; i < this.resinfo.length; i++) {
        if (this.resinfo[i].account === user) {
          this.userInfo = this.resinfo[i]; // 将匹配到的数据存入userInfo对象
          break;
        }
      }
    })
      .catch(error => {
        console.log(error);
      })
  },
  methods: {
    handleClose() {
      this.$router.push("/");
    },
    openWallet(ID) {
      this.$prompt('单位（元）', '请输入您要充值的金额', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.$axios.put("http://localhost:3000/users/" + ID, {
          account: this.userInfo.account,
          password: this.userInfo.password,
          fullname: this.userInfo.fullname,
          sex: this.userInfo.sex,
          email: this.userInfo.email,
          birthday: this.userInfo.birthday,
          address: this.userInfo.address,
          wallet: Number(this.userInfo.wallet) + Number(value),
        }).then(response => {
          this.$message({
            type: 'success',
            message: '充值成功！本次充值金额为：' + Number(value) + '元'
          });
          this.$router.push("/");
        }).catch(error => {
          console.log(error);
          this.$message({
            type: 'error',
            message: '充值失败，请重试！'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消充值'
        });
      });
    },

    //验证邮箱格式
    validateEmail(email) {
      var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return pattern.test(email);
    },

    //验证密码格式
    validatePassword(password) {
      var pattern = /^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]{8,16}$/;
      return pattern.test(password);
    },

    UpdateUser(ID) {
      //验证不能为空
      if (!this.userInfo.account || !this.userInfo.password || !this.userInfo.email) {
        this.$message.error('账号、密码、邮箱为必填项！');
        return;
      }

      if (!this.validatePassword(this.userInfo.password)) {
        this.$message.error('只能输入8-16位数字加字母组成的密码！');
        return;
      }

      if (!this.validateEmail(this.userInfo.email)) {
        this.$message.error('请输入正确的邮箱格式！');
        return;
      }
      this.$axios.put("http://localhost:3000/users/" + ID, {
        account: this.userInfo.account,
        password: this.userInfo.password,
        fullname: this.userInfo.fullname,
        sex: this.userInfo.sex,
        email: this.userInfo.email,
        birthday: this.userInfo.birthday,
        address: this.userInfo.address,
        wallet: this.userInfo.wallet,
      }).then(response => {
        this.$message({
          type: 'success',
          message: '个人信息修改成功啦！'
        });
        this.$router.push("/");
      }).catch(error => {
        console.log(error);
        this.$message({
          type: 'error',
          message: '个人信息修改失败，请重试！'
        });
      });
    },
    gotoOrder(){
      this.$router.push("/order");
    }

  }
}
</script>

<style scoped>
ul {
  padding: 50px;
  list-style: none;
}

li {
  font-size: 16px;
  text-decoration: none;
}

span {
  line-height: 40px;
}

.wallet {
  color: red;
  font-weight: bold;
}
</style>
